package com.huaxin.hxmodulestatisticalanalysis.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.huaxin.hxmodulestatisticalanalysis.DeleteOperationContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
        String userId = UserContext.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            userId = "admin";
        }
        this.strictInsertFill(metaObject, "createdBy", String.class, userId);
        if (metaObject.hasSetter("orgId") && metaObject.getValue("orgId") == null) {
            String currentOrgId = UserContext.getCurrentOrgId();
            if (StringUtils.isBlank(currentOrgId)) {
                currentOrgId = "default";
            }
            this.strictInsertFill(metaObject, "orgId", String.class, UserContext.getCurrentOrgId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = UserContext.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            userId = "admin";
        }
        if (DeleteOperationContext.isDeleteOperation()) {
            this.strictUpdateFill(metaObject, "deletedAt", LocalDateTime.class, LocalDateTime.now());
            this.strictUpdateFill(metaObject, "deletedBy", String.class, userId);
        } else {
            this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
            this.strictUpdateFill(metaObject, "updatedBy", String.class, userId);
        }
    }

    // ✅ 删除 getCurrentUserId() 和 getCurrentOrgId() 方法，它们现在由 UserContext 提供
    // public String getCurrentUserId() { ... }
    // public String getCurrentOrgId() { ... }

    private String getGeneratedUUID() {
        return java.util.UUID.randomUUID().toString();
    }
}
